package stuttgart.uni.pedometer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.util.Log;

/* GpxDataSaver generates/creates a gpx file and
 * Saves Latitude Longitude and Time Data Queued by storePosition function
 */

public class GpxDataSaver extends Thread{
	
	private File storedData;
	private PrintWriter printWriter;
	private WriteToStorageJobs<String> writeJobs;
	private SimpleDateFormat dateFormat;
	
	/* 
	 * */
	public GpxDataSaver(File targetFile){
		Log.d("GpxDataSaver","GpxDataSaver enter Constructor");
    	
    	dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    	
    	storedData = targetFile;
    	storedData.mkdir();
    	storedData.delete();
    	try {
			storedData.createNewFile();
		} catch (IOException e1) {
			Log.d("GpxDataSaver","could not create File");
		}
    	try {
			printWriter = new PrintWriter(storedData);
		} catch (FileNotFoundException e) {
			Log.d("GpxDataSaver","could not create PrintWriter");
		}
    	
    	writeJobs = new WriteToStorageJobs<String>();
    	start();
    	Log.d("GpxDataSaver","GpxDataSaver finished Constructor");
	}
	
	//adds position to write queue
	public void storePosition(PedometerData data){
		writeJobs.add("<trkpt lat=\""+data.getLatitude()+"\" lon=\""+data.getLongitude()+"\">"+"\n<ele>0.0</ele>\n<time>"+dateFormat.format(new Date(data.getTime()))+"</time>\n</trkpt>");
	}
	
	public void close(){
		Log.d("GpxDataSaver", "close called");
		writeJobs.add(null);
	}
	
	public void run() {
		String msg = "";
		
		//write GPX entry
		Log.d("GpxDataSaver", "writing entry");
		printWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>");
		printWriter.println("<gpx version=\"1.1\" creator=\"Andre Oeschger\"> ");
		printWriter.println(" <metadata> <!-- Metadaten --> </metadata> ");
		printWriter.println("<trk>");
		printWriter.println("<trkseg>");
		Log.d("GpxDataSaver", "entry written");

		while (msg != null) {

			try {
				//get String form queue
				msg = writeJobs.poll();
			} catch (InterruptedException e) {
				Log.d("GpxDataSaver", "InterruptedException");
			}
			
			Log.d("GpxDataSaver", "msg is: "+msg);
			
			if (msg != null) {
				Log.d("GpxDataSaver", "writing data");
				//writes sting to file
				printWriter.println(msg);
			}
		}

		//write GPX closing
		Log.d("GpxDataSaver", "writing closing");
		printWriter.println("</trkseg>");
		printWriter.println("</trk>");
		printWriter.println("</gpx>");
		Log.d("GpxDataSaver", "closing written");
		printWriter.close();
		Log.d("GpxDataSaver", "closed");
		
	}
	
}
